"use strict";
const Command = require("@wenjun-cli/command");
const path = require("path");
const log = require("@wenjun-cli/log");
const inquirer = require("inquirer");
const { spinnerStart } = require("@wenjun-cli/utils");
const request = require("@wenjun-cli/request");
const userHome = require("user-home");
const fs = require("fs");
// 自定义常量
const DEFAULT_CLI_HOME = ".wenjun-cli";
const LOGIN_TOKEN_FILE = ".login_token";
class LoginCommand extends Command {
  init() {}
  async exec() {
    // 第一步：输入用户名
    const username = (
      await inquirer.prompt({
        type: "input",
        name: "username",
        message: "请输入用户名：",
      })
    ).username;
    const password = (
      await inquirer.prompt({
        type: "password",
        name: "password",
        message: "请输入密码：",
      })
    ).password;
    // 第二步：登录操作
    const spinner = spinnerStart("登陆中.........");
    try {
      const res = await request.post(
        "/user/login",
        { username, password },
        {
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      spinner.stop(true);
      if (res.code === 0) {
        const tokenFilePath = path.resolve(
          userHome,
          DEFAULT_CLI_HOME,
          LOGIN_TOKEN_FILE
        );
        fs.writeFileSync(tokenFilePath, res.data.token);
        return log.success("登录成功！");
      }
      log.error(res.message);
    } catch (e) {
      spinner.stop(true);
      log.error("登录出错，稍后重试！");
    }
  }
}

function login(argv) {
  log.verbose("login argv", argv);
  return new LoginCommand(argv);
}

module.exports = login;
module.exports.LoginCommand = LoginCommand;
